'use strict';

module.exports = app => {
  class APIController extends app.Controller {
      /**
     * Json way to output.
     * @public
     * @param {String} message
     * @param {Object} data
     * @param {Integer} statusCode
     * @param {String} message
     */
    json(data, statusCode, statusText = null) {
      this.header['Content-type'] = 'application/json';
      this.status = statusCode;
      this.body = data;
      if (statusText) { this.message = statusText; }
    }

    /**
     * Output an normal formatted data after operate success.
     * @param {Mixed} data the output data
     * @param {String} appended message
     */
    success(data, statusCode = 200, message = null) {
      this.json(data, 200, message);
    }

    /**
     * Output an unusual formatted data, normally after operate failed.
     * @param {String} message error message
     * @param {Number} statusCode
     * @param {String} statusText
     */
    fail(message, statusCode = -1, statusText = null) {
      this.json({ message }, statusCode, statusText);
    }
  }

  class CustomService extends app.Service {

    success(result, message) {
      return {
        errcode: 0,
        result,
        message,
      };
    }

    fail(message, errcode) {
      errcode = errcode || -1;
      return {
        errcode,
        message,
      };
    }
  }

  app.APIController = APIController;
  app.Service = CustomService;

};
